<?php
/**
 * Created by PhpStorm.
 * User: yanghaize
 * Date: 16-12-30
 * Time: 下午2:47
 * 公用的插件服务
 */

namespace Inbound\Service;
use Inbound\Model\CommoninterfaceModel;
class PublicPlugService
{

    public static $link;

    public static $flag;

    public static $fla;


    /**
     * 共用的下载方法
     * 获取数据资源
     * @param  string  原生sql
     * @return array
     */
    public static function download($sql)
    {
        set_time_limit(0);

        ini_set("memory_limit","2048M");

        $model=new CommoninterfaceModel();

        $config=$model->host;

        self::$link = mysqli_connect($config['DB_HOST'],$config['DB_USER'],$config['DB_PWD'],$config['DB_NAME']);

        mysqli_query(self::$link,"SET NAMES 'UTF8'");

        if(!self::$link){
            die('Could not connect: '.mysqli_error(self::$link));
        }

        $result = mysqli_query(self::$link,$sql);

        if(!$result){
            echo 'Could not run query: '.mysqli_error(self::$link);
            exit;
        }

        return $result;
    }

    /**
     * 下载示例
     * @param  array
     * @return array
     */
    public function Tdownload()
    {
        set_time_limit(0);

        ini_set('memory_limit','2048M');
        //告诉浏览器这个是一个csv文件
        $fileName = "特殊入库明细报表下载".date('Y-m-d',time());

        header("Content-Type: application/csv");

        header("Content-Disposition: attachment;filename=$fileName.csv");

        if(!empty($_GET)){

            $sql = D('Otherstock','Model')->otherstock_detail_sql($_GET);

            $result = self::download($sql);

            $tableHead = array(
                "特殊入库明细单号",
                "主体",
                "中转仓",
                "特殊入库日期",
            );
            $data      = "序号";

            foreach($tableHead as $value){
                $data .= ",".$value;
            }

            $data .= "\n";
            $i = 0;
            while($row = mysqli_fetch_array($result)){
                $i++;

                $data .= $i.",".$row['id'].",".$row['pd_time'].",".$row['cardboard_code'].",".$row['sku_name'];
                $data .= "\n";
            }
            ob_end_flush();
            echo $data;
            //关闭数据库资源
            mysqli_close(self::$link);
            exit;
        }
    }

    /**
     * 解析表格,返回处理后的数据
     * 支持xlsx,xls,csv格式的表格
     * @param  array
     * @return array
     * 
     */
    public static function parse_excel()
    {
        set_time_limit(0);

        ini_set('memory_limit','2048M');
        if($_FILES['file']['size']>0||$_FILES['excel']['size']>0){

            import("ORG.Util.UploadFile");                        //引入文件上传类

            $config = array(
                'allowExts' => array(
                    'xlsx',
                    'xls',
                    'csv'
                ),
                //设置配置信息
                'savePath'  => './Public/uploads/',
                'saveRule'  => 'time'
            );
            $upload = new \Org\Util\UploadFile($config);
            if(!$upload->upload()){
                self::$flag = $upload->getErrorMsg();
            }else{
                $info = $upload->getUploadFileInfo();
            }

            vendor("PHPExcel.PHPExcel");//获取上传文件信息 加载excel处理工具
            if(!empty($info)){
                $file_name = $info[0]['savepath'].$info[0]['savename'];
                if($info[0]['extension']=='xls'){
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                }elseif($info[0]['extension']=='xlsx'){
                    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                }elseif($info[0]['extension']=='csv'){
                    $objReader = \PHPExcel_IOFactory::createReader('CSV')
                        ->setDelimiter(',')
                        ->setEnclosure('"')
                        ->setLineEnding("\r\n")
                        ->setSheetIndex(0);
                    $objReader->setReadDataOnly(TRUE);
                }

                $objPHPExcel = $objReader->load($file_name,$encode = 'utf-8');

                $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);

            }
            self::$flag = empty($sheetData)?TRUE:FALSE;
            unset($_FILES);
            return $sheetData;
        }else{
            self::$flag = TRUE;
        }
    }

    /**
    * 调用批量导入表格数据处理示例
    * */
    public function format_data()
    {
        $data = self::parse_excel();

        $prepackage = D('','Model');

        $prepackage->init();

        $this->_otherstock = array(
            'store'   => $_POST['store'],
            'create_time'=> date('Y-m-d H:i:s',time()),
            'transfer_hopper_id'=>'1',
            'enterprise_dominant'=>'1',
            'user_id' => $_SESSION['current_account']['id'],
            'status'  => 10,
        );

        $_transfer_order_id = $prepackage->model->table("$this->_db.twms_transfer_order")
            ->add($this->_otherstock);

        $packing_id = '';

        if(!self::$flag){

            foreach($data AS $k => &$v){
                if($k>=2){

                    $v['H']          = trim($v['H']);
                    $this->condition = array('packing_id' => $v['H']);
                    $_param          = self::get_field_by_param($this->condition,array('status'));

                    switch($_param['status']){
                        case'10';
                            $fla = $v['H']."装箱单为未打印状态";
                            break;
                        case'20';
                            $fla = $v['H']."装箱单为已打印但未入库状态";
                            break;
                        case'50';
                            $fla = $v['H']."装箱单为待发货状态";
                            break;
                        case'55';
                            $fla = $v['H']."装箱单为仓内调拨(已调拨出库)状态";
                            break;
                        case'60';
                            $fla = $v['H']."装箱单为仓外调拨(已调拨出库)状态";
                            break;
                        case'65';
                            $fla = $v['H']."装箱单已正常出库";
                            break;
                        case'70';
                            $fla = $v['H']."装箱单已发货";
                            break;
                    }
                    if(empty($_param)){
                        $fla = "您的表格存在格式不对,或是有空格导致创建失败等问题";
                        break;
                    }
                    if($fla){
                        break;
                    }
                    $packing_id .= $packing_id==''?$v['H']:','.$v['H'];
                }
            }

            if(!$fla){
                $map['packing_id'] = array(
                    'in',
                    $packing_id
                );

                self::$fla = $prepackage->update($map,array(
                    'transfer_order_id' => $_transfer_order_id,
                    'status'            => 60
                ),$prepackage->model);
            }
        }else{
            $fla = "请选择上传文件";
        }

        if(!$fla && self::$flag){
            $fla = $_transfer_order_id;

            $prepackage->model->commit();
        }else{
            $prepackage->model->rollback();

        }

        return $fla;
    }
    /**
     * 公用导入模板csv
     * khq 2016.12.30
     **/
    public static function download_templet()
    {
        set_time_limit(0);
        ini_set('memory_limit','2048M');
        //为fputcsv()函数打开文件句柄
        $outPut = fopen('php://output','w') or die("can't open php://output");
        //告诉浏览器这个是一个csv文件
        $fileName = $_GET['fileName'];
        header("Content-Type: application/csv");
        header("Content-Disposition: attachment;filename=$fileName.csv");
        //输出表头
        $tableHead = explode(',',$_GET['list']);
        fputcsv($outPut,$tableHead);
        $body      = explode(',',$_GET['list1']);
        fputcsv($outPut, $body);
        //关闭文件句柄
        fclose($outPut) or die("can't close php://output");
        exit;
    }
    /**
     * 公用导入模板xls
     * khq 2016.12.30
     **/
    public static function download_templet_xls()
    {

        set_time_limit(0);
        ini_set('memory_limit','2048M');
        vendor('PHPExcel.PHPExcel');

        $tableHead = explode(',',$_GET['list']);
        $body      = explode(',',$_GET['list1']);
        $num = count($tableHead);
        $outputFileName = date('YmdHis',time()).'.xls';
        $PHPExcel = new \PHPExcel();
        $currentSheet = $PHPExcel->getSheet(0);
        $k = 0;
        for($i=65;$i<(65+$num);$i++){
            $currentSheet->setCellValue(chr($i).'1', $tableHead[$k]);
            $currentSheet->setCellValue(chr($i).'2', $body[$k]);
            $k+=1;
        }
        $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
        ob_start();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
        header('Pragma: public');
        header('Expires: 30');
        header('Cache-Control: public');
        $PHPWriter->save('php://output');


        //输出表头

    }
    /**
     * 公用导入模板xlsx
     * kelvin 2017.03.30
     **/
    public static function download_templet_xlsx()
    {

        set_time_limit(0);
        ini_set('memory_limit','2048M');
        vendor('PHPExcel.PHPExcel');

        $tableHead = explode(',',$_GET['list']);
        $body      = explode(',',$_GET['list1']);

        if (isset($body[5]) && $body[5]== "正常在售") {
            $body[5] = "正常在售\r\n正常在售（国内发货）\r\n新品在售\r\n新品未上架\r\n缺货\r\n清库存\r\n受限\r\n下架";
        }

        $num = count($tableHead);
        if($_GET['fileName']){
            $outputFileName = $_GET['fileName'].'.xlsx';
        }else{
            $outputFileName = date('YmdHis',time()).'.xlsx';
        }
        $PHPExcel = new \PHPExcel();
        $currentSheet = $PHPExcel->getSheet(0);
        $k = 0;
        for($i=65;$i<(65+$num);$i++){
            $currentSheet->setCellValue(chr($i).'1', $tableHead[$k]);
            $currentSheet->setCellValue(chr($i).'2', $body[$k]);
            $k+=1;
        }
        $PHPWriter = new \PHPExcel_Writer_Excel2007($PHPExcel);
        ob_start();
        header("Content-Type: application/force-download");
        header("Content-Type: application/octet-stream");
        header("Content-Type: application/download");
        header('Content-Disposition:attachment;filename="' .$outputFileName. '"');//输出模板名称
        header("Content-Transfer-Encoding: binary");
        header("Last-Modified:".gmdate("D, d M Y H:i:s")." GMT");
        header('Pragma: public');
        header('Expires: 30');
        header('Cache-Control: public');
        $PHPWriter->save('php://output');


        //输出表头

    }

}